package edu.nf.supermarket.web.controller.app;

import edu.nf.supermarket.base.BaseController;
import edu.nf.supermarket.config.FilePathConfig;
import edu.nf.supermarket.entity.CommentImage;
import edu.nf.supermarket.entity.Comments;
import edu.nf.supermarket.mapper.CommentMapper;
import edu.nf.supermarket.result.ResultVO;
import edu.nf.supermarket.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * @author yjj
 * @date 2025-06-10
 */
@RestController
@RequestMapping("/comment")
public class CommentController extends BaseController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private FilePathConfig filePathConfig;

    /**
     * 获取所有的评论
     */
    @GetMapping("/listComment")
    public ResultVO<List<Comments>> listComment(@RequestParam("productId") Integer productId) {
        return success(commentService.listComment(productId));
    }

    /**
     * 评论筛选分别获取好评、中评、差评
     */
    @GetMapping("/listCommentByDESC")
    public ResultVO<List<Comments>> listCommentByDESC(@RequestParam("grade") Byte grade,
                                                      @RequestParam("productId") Integer productId) {
        return success(commentService.findCommentGoofOrBad(grade, productId));
    }

    /**
     * 获取最新的评论
     */
    @GetMapping("/listNewComment")
    public ResultVO<List<Comments>> listNewComment(@RequestParam("productId") Integer productId) {
        return success(commentService.listCommentByDESC(productId));
    }

    /**
     * 删除评论
     */
    @GetMapping("/deleteComment")
    public ResultVO<String> deleteComment(@RequestParam("commentId") Integer commentId) {
        commentService.deleteComment(commentId);
        return success("删除成功");
    }

    /**
     * 获取该用户所有评论
     */
    @GetMapping("/listCommentByUserId")
    public ResultVO<List<Comments>> listCommentByUserId(@RequestParam("userId") Integer userId) {
        return success(commentService.listCommentByUserId(userId));
    }

    /**
     * 添加评论
     */
    @PostMapping("/addComment")
    public ResultVO<Integer> addComment(@RequestParam("userId") Integer userId,
                                        @RequestParam("orderId") String orderId,
                                        @RequestBody Comments comments) {

        Integer i = commentService.addComment(comments, userId, orderId);
        return success(i);
    }

    /**
     * 添加评论图片
     */
    @PostMapping("/addCommentImages")
    public ResultVO<String> addCommentImages(@RequestParam("commentId") Integer commentId,
                                             @RequestParam(name = "images", defaultValue = "") MultipartFile[] image) throws IOException {
        if (image == null) {
            return success();
        }
        if (image.length == 0) {
            return success();
        }

        // 使用配置的路径
        String uploadDir = filePathConfig.getCommentPath();

        // 处理跨平台路径
        Path uploadPath = Paths.get(uploadDir).normalize();
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        for (MultipartFile file : image) {
            if (!isValidFileType(file.getContentType())) {
                return fail(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(), "文件格式错误");
            }
            //获取文件名称
            String fileName = UUID.randomUUID() + "." + getFileExtension(file.getOriginalFilename());
            Path filePath = uploadPath.resolve(fileName);
            try {
                file.transferTo(filePath.toFile());
            } catch (IOException e) {
                return fail(HttpStatus.FAILED_DEPENDENCY.value(), "上传失败");
            }
            String relativePath = "/static/photo/comments/" + fileName;
            commentService.addCommentImages(commentId, new CommentImage(null,relativePath, LocalDateTime.now()));
        }
        return success("上传成功");
    }
    // 获取文件扩展名
    private String getFileExtension(String filename) {
        return filename.substring(filename.lastIndexOf(".") + 1);
    }

    /**
     * 校验文件类型
     *
     * @return
     */
    public boolean isValidFileType(String fileType) {
        String[] validFileTypes = {"image/jpeg", "image/png", "image/gif","image/webp"};
        for (String type : validFileTypes) {
            if (type.equals(fileType)) {
                return true;
            }
        }
        return false;
    }
}
